<!-- 单位编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="600"
    :model-value="modelValue"
    title="盘点录入"
    @update:model-value="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="仓库" prop="warehouse_id">
        <el-select v-model="form.warehouse_id" placeholder="请选择仓库" clearable>
          <el-option v-for="item in props.warehouseList" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>

      <el-form-item label="商品" prop="product_id">
        <ele-table-select
          ref="selectRef"
          v-model="form.product_id"
          clearable
          placeholder="请选择商品"
          value-key="id"
          label-key="name"
          :table-props="tableProps"
          :popper-width="580"
          @select="select"
          @change="selectChange"
        >
          <template #topExtra>
            <div class="flex-a mb-10px">
              <el-input
                v-model="keyword"
                class="w-200px"
                size="small"
                clearable
                placeholder="搜索商品"
                @clear="selectClear"
                @keyup.enter="selectReload"
                @submit.prevent
              />
              <el-button class="ml-10px" size="small" type="primary" @click="selectReload()">搜索</el-button>
            </div>
          </template>
        </ele-table-select>
      </el-form-item>

      <el-form-item label="盘录数量" prop="multi_unit">
        <div v-if="product.id" class="flex-a">
          <el-space>
            <el-form-item
              v-for="(item, i) in form.multi_unit"
              :key="i"
              :label-width="0"
              :prop="`multi_unit[${i}].num`"
              :required="form.multi_unit.every(v => v.num === '')"
              :show-message="false"
            >
              <el-input
                v-model="item.num"
                class="w-95px!"
                placeholder="数量"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
              >
                <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
              </el-input>
            </el-form-item>
          </el-space>
          <div v-if="form.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px ml-4px text-left">
            = {{ totalUnit(form.multi_unit) }}{{ product.unit }}
          </div>
        </div>
        <div v-else class="flex-a text-warning">
          <el-icon>
            <IconElInfoFilled />
          </el-icon>
          <div class="ml-4px">请先选择商品</div>
        </div>
      </el-form-item>

      <el-form-item label="盘录库位" prop="location_id">
        <template v-if="product.id">
          <el-cascader
            v-model="form.location_id"
            class="w-full"
            :options="locationTree"
            filterable
            clearable
            placeholder="请选择库位"
            :show-all-levels="false"
            :props="{ value: 'id', label: 'name', expandTrigger: 'hover', emitPath: false }"
          />
        </template>

        <div v-else class="flex-a text-warning">
          <el-icon>
            <IconElInfoFilled />
          </el-icon>
          <div class="ml-4px">请先选择商品</div>
        </div>
      </el-form-item>

      <el-form-item v-if="product.id && product.location.length" label="库存明细">
        <el-table :data="product.location" size="small">
          <el-table-column prop="name" label="库位" />
          <el-table-column prop="stock" label="数量" :formatter="row => `${row.stock} ${product.unit}`" />
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { listProduct, listWlList } from '@/api/common'
import { toTree } from 'ele-admin-plus/es'

const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  warehouseList: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['done', 'update:modelValue'])

const { totalUnit } = utils
const locationId = ref()

const selectRef = ref(null)

const keyword = ref('')

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

const tableProps = reactive({
  size: 'small',
  datasource: ({ where, pages, orders }) => {
    return listProduct({ warehouse_id: form.warehouse_id, is_location: 1, ...where, ...orders, ...pages })
  },
  columns: [
    {
      type: 'index',
      columnKey: 'index',
      label: '序',
      width: 50,
      align: 'center',
      fixed: 'left',
    },
    {
      prop: 'name',
      label: '商品名称',
      minWidth: 160,
      showOverflowTooltip: false,
    },
    {
      prop: 'code',
      label: '商品编码',
      width: 100,
      align: 'center',
    },
    {
      prop: 'unit',
      label: '主单位',
      align: 'center',
      width: 100,
    },
    {
      prop: 'location',
      label: '库位',
      formatter: row => row.location?.length ? row.location.map(v => v.name).toString() : '-',
      width: 140,
      align: 'center',
    },
  ],
  highlightCurrentRow: true,
  loadOnCreated: false,
  toolbar: false,
  pagination: {
    pageSize: 6,
    layout: 'total, prev, pager, next, jumper',
  },
  footerStyle: { padding: '0px' },
  rowStyle: { cursor: 'pointer' },
})

const rules = {
  warehouse_id: {
    required: true,
    message: '请选择仓库',
    trigger: 'change',
  },
  product_id: {
    required: true,
    message: '请选择商品',
    trigger: 'change',
  },
  location_id: {
    required: true,
    message: '请选择库位',
    trigger: 'change',
  },
  multi_unit: {
    required: true,
    message: '请选择数量',
    trigger: 'change',
  },
}

/** 表单数据 */
const [form, resetFields] = utils.useFormData({
  warehouse_id: '',
  product_id: undefined,
  location_id: undefined,
  multi_unit: [],
})

const locationList = ref([])
const locationTree = ref([])
const locationTreeFull = ref([])
const product = ref({})

function getLocList() {
  listWlList(form.warehouse_id).then((res) => {
    locationList.value = res.data
    locationTreeFull.value = toTree({
      data: res.data,
      idField: 'id',
      parentIdField: 'pid',
    })
  })
}

function selectClear() {
  keyword.value = ''
  selectReload()
}

function selectReload() {
  const where = { keyword: keyword.value }
  selectRef.value?.tableRef?.reload?.({ where, page: 1 })
  product.value = {}
  form.multi_unit = []
}

function selectChange(value) {
  if (!value) {
    form.multi_unit = []
    form.location_id = ''
  }
}

function select(data) {
  product.value = data
  form.multi_unit = data.unit_list.map(v => ({ ...v, num: '' }))
  if (data.location?.length) {
    form.location_id = data.location[0].id
    // 选data.location的库位和 locationList的type NOTIN data.location
    const types = data.location.map(v => v.type)
    const ids = data.location.map(v => v.id)
    const newLocationList = locationList.value.filter(v => ids.includes(v.id) || !types.includes(v.type))
    locationTree.value = toTree({
      data: newLocationList,
      idField: 'id',
      parentIdField: 'pid',
    })
  }
  else {
    locationTree.value = locationTreeFull.value
    form.location_id = undefined
  }
}

watch(() => form.warehouse_id, (newVal) => {
  if (newVal) {
    getLocList()
    keyword.value = ''
  }
  form.product_id = ''
  selectReload()
})

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    utils.post('/stockInventory/add', {
      ...form,
      num: totalUnit(form.multi_unit),
    })
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          updateModelValue(false)
          emit('done')
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (!modelValue) {
      resetFields()
      formRef.value?.clearValidate?.()
      locationId.value = 0
    }
  },
)
</script>
